import router from '@/router'
import { useLoginUserStore } from '@/stores/loginUserStore.ts'
import ACCESS_ENUM from '@/access/accessEnum.ts'
import { UserControllerService } from '../../openapi'
import checkAccess from '@/access/checkAccess.ts'

router.beforeEach(async (to, from, next) => {
  console.log(to)
  const loginUserStore = useLoginUserStore()
  const loginUser = loginUserStore.loginUser
  console.log(loginUser.userRole)
  //之前没登陆过进行自动登陆
  if (loginUser.userRole !== ACCESS_ENUM.NOT_LOGIN) {
    await loginUserStore.getLoginUser()
  }
  //获取要跳转到的页面的权限
  const needAccess = (to.meta?.access as any) ?? ACCESS_ENUM.NOT_LOGIN
  //要跳转的页面必须要登陆
  if (needAccess !== ACCESS_ENUM.NOT_LOGIN) {

    //没登陆跳转到登陆页面
    if (!loginUser || loginUser.userRole === ACCESS_ENUM.NOT_LOGIN) {
      next(`/user/login`)
      return
    }
    //如果登陆后权限不足，跳转到无权限页面
    if (!checkAccess(loginUser, needAccess)) {
      next(`/noAuth`)
      return
    }
  }
  next()
})
